package com.jweb.framework.ws.soap.axiom;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.RolePlayer;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.SOAPHeader;
import org.apache.axiom.soap.SOAPHeaderBlock;
import org.apache.axiom.soap.SOAPProcessingException;
import org.springframework.util.ObjectUtils;
import org.springframework.ws.soap.SoapHeaderElement;
import org.springframework.ws.soap.SoapHeaderException;
import org.springframework.ws.soap.soap12.Soap12Header;
import org.springframework.xml.namespace.QNameUtils;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：
 */
class AxiomSoap12Header extends AxiomSoapHeader implements Soap12Header {
	
	AxiomSoap12Header(SOAPHeader axiomHeader , SOAPFactory axiomFactory) {
		super(axiomHeader, axiomFactory);
	}
	
	public SoapHeaderElement addNotUnderstoodHeaderElement(QName headerName){
		try {
			SOAPHeaderBlock notUnderstood = getAxiomHeader().addHeaderBlock("NotUnderstood", getAxiomHeader().getNamespace());
			OMNamespace headerNamespace = notUnderstood.declareNamespace(headerName.getNamespaceURI(), QNameUtils.getPrefix(headerName));
			notUnderstood.addAttribute("qname", headerNamespace.getPrefix()+":"+headerName.getLocalPart(), null);
			return new AxiomSoapHeaderElement(notUnderstood, getAxiomFactory());
		} catch (SOAPProcessingException e) {
			throw new AxiomSoapHeaderException(e);
		}
	}
	
	public SoapHeaderElement addUpgradeHeaderElement(String[] supportedSoapUris) {
		
		try {
			SOAPHeaderBlock upgrade = getAxiomHeader().addHeaderBlock("Upgrade", getAxiomHeader().getNamespace());
			for(String supportedSoapUri : supportedSoapUris){
				OMElement supportedEnvelope = getAxiomFactory().createOMElement("SupportedEnvelope", getAxiomHeader().getNamespace() , upgrade);
				OMNamespace namespace = supportedEnvelope.declareNamespace(supportedSoapUri, "");
				supportedEnvelope.addAttribute("qname", namespace.getPrefix()+":Envelope", null);
			}
			return new AxiomSoapHeaderElement(upgrade , getAxiomFactory());
		} catch (OMException e) {
			throw new AxiomSoapHeaderException(e);
		}
		
	}
	
	
	public Iterator<SoapHeaderElement> examineHeaderElementsToProcess(final String[] roles, final boolean isUltimateDestination) throws SoapHeaderException {
		
		RolePlayer rolePlayer = null ;
		if(!ObjectUtils.isEmpty(roles)){
			rolePlayer = new RolePlayer(){
				public List<?> getRoles(){
					return Arrays.asList(roles);
				}
				
				public boolean isUltimateDestination(){
					return isUltimateDestination ;
				}
			};
		}
		Iterator<SOAPHeaderBlock> result = getAxiomHeader().getHeadersToProcess(rolePlayer);
		
		return new AxiomSoapHeader.AxiomSoapHeaderElementIterator(result);
	}
	

}
